package com.dmzc.stage2.chapter22;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.currentThread;

public class Document {
    private boolean changed = false;
    private List<String> content = new ArrayList<>();
    private final FileWriter writer;
    private static AutoSaveThread autoSaveThread;

    private Document(String path, String name) throws IOException {
        this.writer = new FileWriter(new File(path, name));
    }

    public static Document create(String path, String name) throws IOException {
        Document document = new Document(path, name);
        autoSaveThread = new AutoSaveThread(document);
        autoSaveThread.start();
        return document;
    }

    public void edit(String content) {
        synchronized (this) {
            this.content.add(content);
            this.changed = true;
        }
    }
    public void close()throws IOException{
        autoSaveThread.interrupt();
        writer.close();
    }
    public void save() throws IOException{
        if (!changed)
            return;
        System.out.println(currentThread()+"excute the save action");
        for (String cacheLine:content){
            this.writer.write(cacheLine);
            this.writer.write("\r\n");
        }
        this.writer.flush();
        this.changed=false;
        this.content.clear();
    }

}
